<template>
  <div class="app-container verification-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon"><User /></el-icon>
        <span>用户认证审核</span>
      </div>
      <div class="page-description">管理用户实名认证申请，审核身份信息</div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never" v-show="showSearch">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Search /></el-icon>
            筛选条件
          </span>
        </div>
      </template>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="用户ID" prop="userId">
              <el-input
                v-model="queryParams.userId"
                placeholder="请输入用户ID"
                clearable
                @keyup.enter="handleQuery"
                prefix-icon="User"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="queryParams.realName"
                placeholder="请输入真实姓名"
                clearable
                @keyup.enter="handleQuery"
                prefix-icon="User"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号" prop="idCardNo">
              <el-input
                v-model="queryParams.idCardNo"
                placeholder="请输入身份证号"
                clearable
                @keyup.enter="handleQuery"
                prefix-icon="CreditCard"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery" class="search-btn">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery" class="reset-btn">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" shadow="never">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Check"
            :disabled="multiple"
            @click="handleBatchApprove"
            v-hasPermi="['verification:verification:edit']"
            class="operation-btn"
          >一键通过</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['verification:verification:export']"
            class="operation-btn"
          >导出数据</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><List /></el-icon>
            认证申请列表
          </span>
          <div class="table-info">
            <el-tag type="info" size="small">共 {{ total }} 条记录</el-tag>
          </div>
        </div>
      </template>
      <el-table 
        v-loading="loading" 
        :data="verificationList" 
        @selection-change="handleSelectionChange"
        class="verification-table"
        stripe
        border
        :header-cell-style="{ background: '#f8f9fa', color: '#606266', fontWeight: 'bold' }"
        style="width: 100%"
        table-layout="auto"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="认证ID" align="center" prop="verificationId" min-width="80">
          <template #default="scope">
            <el-tag type="info" size="small">#{{ scope.row.verificationId }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" align="center" min-width="120">
          <template #default="scope">
            <div class="user-info">
              <div class="real-name">{{ scope.row.realName || '未填写' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" align="center" prop="idCardNo" min-width="160" show-overflow-tooltip>
          <template #default="scope">
            <span class="id-card-no">{{ scope.row.idCardNo || '未填写' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="认证图片" align="center" min-width="280">
          <template #default="scope">
            <div class="verification-images">
              <!-- 身份证正面 -->
              <div class="image-card" v-if="scope.row.idCardFront">
                <div class="image-label">
                  <el-icon><CreditCard /></el-icon>
                  <span>身份证正面</span>
                </div>
                <div class="image-container">
                  <el-image
                    :src="getImageUrl(scope.row.idCardFront)"
                    :preview-src-list="[getImageUrl(scope.row.idCardFront)]"
                    fit="cover"
                    class="verification-image"
                    :preview-teleported="true"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                </div>
              </div>

              <!-- 身份证背面 -->
              <div class="image-card" v-if="scope.row.idCardBack">
                <div class="image-label">
                  <el-icon><CreditCard /></el-icon>
                  <span>身份证背面</span>
                </div>
                <div class="image-container">
                  <el-image
                    :src="getImageUrl(scope.row.idCardBack)"
                    :preview-src-list="[getImageUrl(scope.row.idCardBack)]"
                    fit="cover"
                    class="verification-image"
                    :preview-teleported="true"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                </div>
              </div>

              <!-- 人脸照片 -->
              <div class="image-card" v-if="scope.row.facePhoto">
                <div class="image-label">
                  <el-icon><User /></el-icon>
                  <span>人脸照片</span>
                </div>
                <div class="image-container">
                  <el-image
                    :src="getImageUrl(scope.row.facePhoto)"
                    :preview-src-list="[getImageUrl(scope.row.facePhoto)]"
                    fit="cover"
                    class="verification-image face-photo"
                    :preview-teleported="true"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                </div>
              </div>

              <!-- 无图片状态 -->
              <div v-if="!scope.row.idCardFront && !scope.row.idCardBack && !scope.row.facePhoto" class="no-verification-images">
                <el-icon><Picture /></el-icon>
                <span>暂无认证图片</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="认证状态" align="center" prop="verificationStatus" min-width="100">
          <template #default="scope">
            <div class="status-wrapper">
              <el-tag 
                :type="scope.row.verificationStatus == 1 ? 'success' : (scope.row.verificationStatus == 2 ? 'danger' : 'warning')"
                :icon="scope.row.verificationStatus == 1 ? 'Check' : (scope.row.verificationStatus == 2 ? 'Close' : 'Clock')"
                size="default"
                effect="dark"
              >
                {{ scope.row.verificationStatus == 0 ? '待审核' : (scope.row.verificationStatus == 1 ? '已通过' : '已拒绝') }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="拒绝原因" align="center" prop="rejectReason" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.rejectReason" class="reject-reason">{{ scope.row.rejectReason }}</span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        <el-table-column label="时间信息" align="center" min-width="160">
          <template #default="scope">
            <div class="time-info">
              <div class="time-item">
                <el-icon><Calendar /></el-icon>
                <span>创建: {{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="180" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                v-if="scope.row.verificationStatus == 0" 
                type="success" 
                size="small"
                icon="Check" 
                plain
                @click="handleApprove(scope.row)" 
                v-hasPermi="['verification:verification:edit']"
                class="action-btn approve-btn"
              >
                通过
              </el-button>
              <el-button 
                v-if="scope.row.verificationStatus == 0" 
                type="danger" 
                size="small"
                icon="Close" 
                plain
                @click="handleReject(scope.row)" 
                v-hasPermi="['verification:verification:edit']"
                class="action-btn reject-btn"
              >
                驳回
              </el-button>
              <el-button 
                type="primary" 
                size="small"
                icon="View" 
                plain
                @click="handleView(scope.row)" 
                v-hasPermi="['verification:verification:query']"
                class="action-btn view-btn"
              >
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="认证详情" v-model="openView" width="80%" append-to-body>
      <div style="max-height: 70vh; overflow-y: auto;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="认证ID">{{ viewForm.verificationId }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ viewForm.userId }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ viewForm.realName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ viewForm.idCardNo }}</el-descriptions-item>
          <el-descriptions-item label="认证状态">
            <el-tag 
              :type="viewForm.verificationStatus == 1 ? 'success' : (viewForm.verificationStatus == 2 ? 'danger' : 'warning')"
            >
              {{ viewForm.verificationStatus == 0 ? '待审核' : (viewForm.verificationStatus == 1 ? '已通过' : '已拒绝') }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="拒绝原因">{{ viewForm.rejectReason || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ viewForm.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ viewForm.updatedAt }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 认证图片展示 -->
        <div class="verification-images-detail" style="margin-top: 20px;">
          <h4>认证图片</h4>
          <el-row :gutter="20">
            <el-col :span="8" v-if="viewForm.idCardFront">
              <div class="image-detail-card">
                <h5>身份证正面</h5>
                <el-image
                  :src="getImageUrl(viewForm.idCardFront)"
                  :preview-src-list="[getImageUrl(viewForm.idCardFront)]"
                  fit="cover"
                  style="width: 100%; height: 200px; border-radius: 8px;"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
            </el-col>
            <el-col :span="8" v-if="viewForm.idCardBack">
              <div class="image-detail-card">
                <h5>身份证背面</h5>
                <el-image
                  :src="getImageUrl(viewForm.idCardBack)"
                  :preview-src-list="[getImageUrl(viewForm.idCardBack)]"
                  fit="cover"
                  style="width: 100%; height: 200px; border-radius: 8px;"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
            </el-col>
            <el-col :span="8" v-if="viewForm.facePhoto">
              <div class="image-detail-card">
                <h5>人脸照片</h5>
                <el-image
                  :src="getImageUrl(viewForm.facePhoto)"
                  :preview-src-list="[getImageUrl(viewForm.facePhoto)]"
                  fit="cover"
                  style="width: 100%; height: 200px; border-radius: 8px;"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!-- 驳回原因对话框 -->
    <el-dialog title="驳回认证" v-model="openReject" width="500px" append-to-body>
      <el-form ref="rejectRef" :model="rejectForm" :rules="rejectRules" label-width="80px">
        <el-form-item label="驳回原因" prop="rejectReason">
          <el-input 
            v-model="rejectForm.rejectReason" 
            type="textarea" 
            :rows="4"
            placeholder="请输入驳回原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openReject = false">取 消</el-button>
          <el-button type="danger" @click="confirmReject">确认驳回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Verification">
import { listVerification, getVerification, delVerification, addVerification, updateVerification, approveVerification, rejectVerification } from "@/api/verification/verification";

const { proxy } = getCurrentInstance();
const { parseTime } = proxy.useDict();

const verificationList = ref([]);
const open = ref(false);
const openView = ref(false);
const openReject = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  viewForm: {},
  rejectForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    realName: null,
    idCardNo: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    realName: [
      { required: true, message: "真实姓名不能为空", trigger: "blur" }
    ],
    idCardNo: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ]
  },
  rejectRules: {
    rejectReason: [
      { required: true, message: "驳回原因不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, viewForm, rejectForm, rules, rejectRules } = toRefs(data);

/** 查询认证审核列表 */
function getList() {
  loading.value = true;
  listVerification(queryParams.value).then(response => {
    verificationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    verificationId: null,
    userId: null,
    realName: null,
    idCardNo: null,
    idCardFront: null,
    idCardBack: null,
    facePhoto: null,
    verificationStatus: null,
    rejectReason: null,
    verifiedTime: null,
    createdAt: null,
    updatedAt: null
  };
  proxy.resetForm("verificationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.verificationId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查看详情操作 */
function handleView(row) {
  const _verificationId = row.verificationId;
  getVerification(_verificationId).then(response => {
    viewForm.value = response.data;
    openView.value = true;
  });
}

/** 通过认证 */
function handleApprove(row) {
  proxy.$modal.confirm('是否确认通过该用户的认证申请？').then(function() {
    return approveVerification(row.verificationId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("认证通过成功");
  }).catch(() => {});
}

/** 驳回认证 */
function handleReject(row) {
  rejectForm.value = {
    verificationId: row.verificationId,
    rejectReason: ''
  };
  openReject.value = true;
}

/** 确认驳回 */
function confirmReject() {
  proxy.$refs["rejectRef"].validate(valid => {
    if (valid) {
      rejectVerification(rejectForm.value).then(response => {
        proxy.$modal.msgSuccess("驳回成功");
        openReject.value = false;
        getList();
      });
    }
  });
}

/** 批量通过 */
function handleBatchApprove() {
  const verificationIds = ids.value;
  proxy.$modal.confirm('是否确认批量通过选中的认证申请？').then(function() {
    return Promise.all(verificationIds.map(id => approveVerification(id)));
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("批量通过成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('verification/verification/export', {
    ...queryParams.value
  }, `verification_${new Date().getTime()}.xlsx`)
}

/** 获取图片URL */
function getImageUrl(url) {
  if (!url) return '';
  if (url.startsWith('http')) return url;
  return import.meta.env.VITE_APP_BASE_API + url;
}

getList();
</script>

<style scoped>
.verification-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.title-icon {
  margin-right: 12px;
  font-size: 28px;
}

.page-description {
  font-size: 14px;
  opacity: 0.9;
}

.search-card, .operation-card, .table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.card-title .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.verification-images {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
}

.image-card {
  text-align: center;
}

.image-label {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.image-label .el-icon {
  margin-right: 4px;
}

.verification-image {
  width: 80px;
  height: 50px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.face-photo {
  width: 50px;
  height: 50px;
}

.no-verification-images {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 12px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-btn {
  margin: 0;
}

.status-wrapper {
  display: flex;
  justify-content: center;
}

.time-info {
  font-size: 12px;
}

.time-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.time-item .el-icon {
  margin-right: 4px;
  color: #909399;
}

.user-info {
  text-align: center;
}

.real-name {
  font-weight: bold;
  color: #303133;
}

.id-card-no {
  font-family: monospace;
}

.reject-reason {
  color: #f56c6c;
}

.text-placeholder {
  color: #c0c4cc;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-detail-card {
  text-align: center;
}

.image-detail-card h5 {
  margin-bottom: 10px;
  color: #606266;
}

.search-btn {
  margin-right: 10px;
}

.operation-btn {
  margin-right: 10px;
}
</style>